<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <!--溯源流程项目数据-->
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" v-show="showSearch" >
          <el-form-item label="物流码" prop="transportCode">
            <el-input v-model="queryParams.transportCode" placeholder="请输入物流码" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="操作员" prop="operatorName">
            <el-input v-model="queryParams.operatorName" placeholder="请输入操作员" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="流程类别" prop="trackingCategoryName">
            <el-input v-model="queryParams.trackingCategoryName" placeholder="请输入流程类别" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="流程说明" prop="description">
            <el-input v-model="queryParams.description" placeholder="请输入流程说明" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="操作时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>

          <el-form-item>
            <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" v-hasPermi="['batchSaveTrackingProcessItem']"  icon="el-icon-plus" size="mini" @click="handleAdd">批量新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" v-hasPermi="['updateTrackingProcessItem']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" v-hasPermi="['deleteTrackingProcessItem']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
          </el-col>

          <right-toolbar :showSearch.sync="showSearch" @queryTable="queryTrackingProcessItemPageResList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center"/>
          <el-table-column label="物流码" align="left" prop="transportCode"  width="200" />
          <el-table-column label="流程类别" align="left" prop="trackingCategoryName" width="200" />
          <el-table-column label="操作时间" align="left" prop="operationTime" sortable='custom' width="200" />
          <el-table-column label="操作员" align="left" prop="operatorName" width="150" />
          <el-table-column label="流程说明" align="left" prop="description"/>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateTrackingProcessItem']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" v-hasPermi="['deleteTrackingProcessItem']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
                    @pagination="queryTrackingProcessItemPageResList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">
        <el-form-item label="流程类别" prop="trackingCategoryId">
          <el-select :hide-required-asterisk="true" v-model="form.trackingCategoryId" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in trackingCategoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="物流码" prop="transportCode" v-if="form.itemId===undefined"  :rules="{required: true, message: '物流码必须录入一个'}">
          <el-input type="textarea" autocomplete="off" :rows="4"  v-model="form.transportCode" placeholder="录入物流码，支持扫描枪，一行一个，回车换行"/>
        </el-form-item>

        <el-form-item label="流程说明" prop="description">
          <el-input autocomplete="off" v-model="form.description" placeholder="请输入流程记录的简要说明" maxlength="250" />
        </el-form-item>

        <el-form-item label="操作时间" prop="operationTime" >
          <el-date-picker
            style="width: 100%;"
            v-model="form.operationTime"
            type="datetime"
            placeholder="选择流程发生的时间，将会展示在流程追溯内容和列表中"
            align="right"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="操作员" prop="operatorName">
          <el-input autocomplete="off" v-model="form.operatorName" placeholder="请输入填写负责人姓名或工号" maxlength="20" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {queryTrackingProcessItemPageResList, batchSaveTrackingProcessItem, updateTrackingProcessItem, deleteTrackingProcessItemByItemId} from '@/api/tracking/trackingProcessItem'
  import {querySelectNormalTrackingCategoryResList } from '@/api/tracking/trackingCategory'
  //默认查询参数
  let defaultQueryParams = {
    transportCode: undefined,
    trackingCategoryName: undefined,
    description: undefined,
    operatorName: undefined,
    startTime: undefined,
    endTime: undefined,
    page: 1,
    rows: 10
  }
  export default {
    name: "trackingProcessItemAdmin",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        // table表格数据
        dataList: [],
        // 日期范围
        dateRange: [],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        //流程类别选项
        trackingCategoryOptions: [],
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //列信息
        columns: [],
        //时间范围
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        // 新增修改表单校验
        addUpdateOpenRules: {
          trackingCategoryId: [
            { required: true, message: "流程类别必须选择"}
          ],
          operationTime: [
            { required: true, message: "操作时间必须填写"}
          ],
          operatorName: [
            { required: true, message: "操作员不能为空"}
          ],
          description: [
            { required: true, message: "流程说明不能为空"}
          ]
        },
      }
    },
    created() {
      this.queryTrackingProcessItemPageResList();
    },
    methods: {
      /** 流程类别查询 */
      querySelectNormalTrackingCategoryResList() {
        querySelectNormalTrackingCategoryResList({}).then(response => {
          this.trackingCategoryOptions = response.data;
        });
      },

      /** 查询溯源流程项目列表 */
      queryTrackingProcessItemPageResList() {
        this.loading = true
        queryTrackingProcessItemPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.loading = false
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.itemId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column){
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.queryTrackingProcessItemPageResList()
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.querySelectNormalTrackingCategoryResList();
        this.addUpdateOpen = true;
        this.title = "添加溯源流程记录";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.form = {...row};
        this.querySelectNormalTrackingCategoryResList();
        this.addUpdateOpen = true;
        this.title = "修改溯源流程记录";
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选溯源流程记录?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const itemId={itemId:row.itemId}
          return deleteTrackingProcessItemByItemId(itemId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryTrackingProcessItemPageResList();
        }).catch(function() {});
      },

      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.itemId !== undefined) {
              updateTrackingProcessItem(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryTrackingProcessItemPageResList();
                this.addUpdateOpen = false
              });
            }else {
              this.form.transportCodeList = [];
              if (this.form.transportCode){
                this.form.transportCodeList = this.form.transportCode.split('\n');
              }
              batchSaveTrackingProcessItem(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryTrackingProcessItemPageResList();
                this.addUpdateOpen = false
              });
            }
          }
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.queryTrackingProcessItemPageResList()
      },
      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = [];
        this.resetForm(fromId);
        this.handleQuery()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.form = {
          itemId:undefined,
          operationTime: undefined,
          transportCode:undefined,
          operatorName: undefined,
          description: undefined,
          trackingCategoryId: "",
          transportCodeList: [],
          trackingCategoryOptions: []
        };
        this.resetForm('form')
      }
    }
  }
</script>
